<template>
  <el-row style="height: 100vh; display: flex" :gutter="20">
    <el-col :span="5" id="left-tree" class="left-tree">
      <div class="comp-tree" style="height: 100%; padding-left: 10px; padding-top: 20px; border-right: 1px solid #dfe6ec; display: block; overflow: auto">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText"> </el-input>
        <el-tree
          class="filter-tree"
          default-expand-all
          :filter-node-method="filterNode"
          ref="SlotTree"
          :default-expanded-keys="treeData"
          :current-node-key="currentNodekey"
          :data="treeList"
          :props="defaultProps"
          :expand-on-click-node="false"
          highlight-current
          :node-key="NODE_KEY"
          @node-click="handleNodeClick"
        >
          <template v-slot="{ node, data }">
            <el-tooltip :content="data.label" placement="top">
              <span>{{ data.label }}</span>
            </el-tooltip>
          </template>
        </el-tree>
        <!-- <div id="resize" class="resize" title="收缩侧边栏">
          <p>⋮</p>
        </div> -->
      </div>
      <!-- </div>
    </div> -->
    </el-col>
    <!-- <el-col :span="6">
      <div class="app-container calendar-list-container">
        <div id="treeBox" class="filter-container">
          <el-table :data="treeList" style="width: 100%;" row-key="id" border lazy :load="load"
            @row-click="getListByTreeId">
            <el-table-column prop="name" label="名称" sortable />
          </el-table>
        </div>
      </div>
    </el-col> -->
    <el-col id="right-content" class="right-content" :offset="0" :span="18">
      <div class="app-container">
        <div class="filter-container">
          <div class="filter-item">
            <span class="span">字段名称:</span>
            <el-input v-model="listQuery.columnName" placeholder="请输入字段名称" style="width: 200px" />
          </div>
          <div class="filter-item">
            <span class="span">字段注解:</span>
            <el-input v-model="listQuery.columnComment" placeholder="请输入字段注解" style="width: 200px" />
          </div>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            {{ $t('table.search') }}
          </el-button>

          <!--          <el-button v-waves v-permission="['metadata:column:add']" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">-->
          <!--            {{ $t('table.add') }}-->
          <!--          </el-button>-->
          <!--          <el-button v-waves v-permission="['metadata:column:delete']" class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleBathDelete">-->
          <!--            {{ $t('table.delete') }}-->
          <!--          </el-button>-->
          <!--          <el-button v-waves v-permission="['metadata:column:import']" class="filter-item" type="primary" icon="el-icon-upload2" @click="handleImport">-->
          <!--            {{ $t('table.import') }}-->
          <!--          </el-button>-->
          <!-- <el-button v-waves v-permission="['metadata:column:export']" :loading="downloadLoading" class="filter-item"
            type="primary" icon="el-icon-download" @click="handleExport">
            {{ $t('table.export') }}
          </el-button> -->
        </div>
        <div class="filter-container">
          <!-- <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
            @click="handleCreate">
            {{ $t('table.entity') }}
          </el-button> -->

          <!-- <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search"
            @click="handleCheck">
            {{ $t('table.checkentity') }}
          </el-button> -->
        </div>

        <el-table ref="table" :key="tableKey" v-loading="listLoading" element-loading-text="正在加载，请稍后" :data="list" border fit highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column align="center" type="index" width="50" label="序号">
            <template slot-scope="scope">
              <span>{{ (listQuery.page - 1) * listQuery.limit + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="拖拽" width="80">
            <template slot-scope="{}">
              <svg-icon class="drag-handler" icon-class="drag" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="表名称" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.tableName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="表注释" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.tableComment }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="字段名称" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.columnName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="字段注释" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.columnComment }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="是否主键" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.columnKey | dictLabel('sf') }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="是否为空" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.columnNullable | dictLabel('sf') }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="数据类型" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.dataType }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="数据长度" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.dataLength }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="数据精度" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.dataPrecision }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="标签" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.label }}</span>
            </template>
          </el-table-column>
        </el-table>

        <import ref="import" template-url="/metadata/column/template" import-url="/metadata/column/import" @refreshList="getList" />
        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" :page-sizes="pageArray" @pagination="getList" />
      </div>
    </el-col>
  </el-row>
</template>
<style>
/* 自定义节点的样式 */
.el-tree-node__content:hover {
  background-color: #e0e0e0;
  cursor: pointer;
}

/* 自定义工具提示的样式 */
.el-tooltip__popper {
  z-index: 9999; /* 确保工具提示显示在顶部 */
}
</style>
<script>
import { fetchsourceList } from '@/api/metadata/source'
import { deletecolumn, fetchcolumnList, exportcolumn, updatecolumn } from '@/api/metadata/column'
import Import from '@/components/Import/import'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission/permission'
import Pagination from '@/components/Pagination'
import Sortable from 'sortablejs'
import { fetchMetadataLabelGroupList } from '@/api/metadata/label/metadataLabelGroup'

export default {
  name: 'columnList',
  components: { Pagination, Import },
  directives: { waves, permission },
  data() {
    return {
      filterText: '',
      tableKey: 0,
      treeList: [],
      labelList: [],
      list: null,
      total: 0,
      multipleSelection: [],
      downloadLoading: false,
      listLoading: true,
      pageArray: this.$store.getters.pageArray,
      listQuery: {
        columnName: undefined,
        ancestralId: '3',
        page: 1,
        limit: this.$store.getters.defaultPageSize,
      },
      entityQuery: {},
      currentNodekey: '',
      treeData: [],
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      NODE_KEY: 'id',
    }
  },
  computed: {
    ids() {
      const ids = []
      this.multipleSelection.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids.join(',')
    },
  },
  created() {
    this.getTreeList()
    // this.getLabelList()
  },
  watch: {
    filterText(val) {
      this.$refs.SlotTree.filter(val)
    },
  },
  mounted() {
    this.dragControllerDiv()
  },
  methods: {
    dragControllerDiv() {
      let left = document.getElementById('left-tree')
      let line = document.getElementById('resize')
      let right = document.getElementById('right-content')
      // 鼠标按下事件
      line.onmousedown = function (e) {
        let startX = e.clientX
        line.left = line.offsetLeft
        // 鼠标拖动事件
        document.onmousemove = function (e) {
          let moveLen = line.left + (e.clientX - startX)
          if (moveLen >= document.body.clientWidth * 0.1 && moveLen <= document.body.clientWidth * 0.4) {
            line.style.left = moveLen + 'px'
            left.style.width = moveLen + 'px'
            right.style.width = document.body.clientWidth - moveLen + 'px'
          }
        }
        document.onmouseup = function () {
          document.onmousemove = null
          document.onmouseup = null
        }
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleNodeClick(data) {
     
      this.listQuery.sourceId = data.id
      this.getList()
    },
    getTreeList() {
      this.listLoading = true
      fetchsourceList(this.listQuery).then((response) => {
        if (response.data.code === 0) {
          this.treeList = response.data.data
          // if(this.treeList.length>0){
          // this.listQuery.directoryId = this.treeList[0].children[0].id
          // this.currentNodekey = this.treeList[0].id;
          // console.log("1====="+this.treeList[0].id)
          // console.log("2====="+this.treeList[0].children[0].id)
          // console.log("3====="+this.treeList[0].children[0].children[0].id)
          // this.treeData.push(this.treeList[0].id,this.treeList[0].children[0].id,this.treeList[0].children[0].children[0].id)
          // this.listQuery.sourceId = this.treeList[0].children[0].children[0].id
          // this.getList()
          //   this.$nextTick(() => {
          //     this.$refs.SlotTree.setCurrentKey(this.treeList[0].children[0].children[0].id); //一定要加这个选中了否则样式没有出来
          //   });
          // }
          this.listLoading = false
          this.$refs.form.setList(this.treeList)
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    getLabelList() {
      this.listLoading = true
      fetchMetadataLabelGroupList(this.listQuery).then((response) => {
        if (response.data.code === 0) {
          this.labelList = response.data.data
          this.listLoading = false
          this.$refs.form.setList(this.labelList)
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },

    //定义实体按钮
    handleCreate() {
      if (this.listQuery.sourceId) {
        this.entityQuery.tableId = this.listQuery.sourceId
        this.$refs.entityform.setList(this.entityQuery)
        this.$refs.entityform.handleCreate()
      } else {
        this.$message.warning('请先选择表')
      }
      // this.$refs.entityform.setList(this.labelList)
    },
    //查看实体按钮
    handleCheck() {
      if (this.listQuery.sourceId) {
        this.entityQuery.tableId = this.listQuery.sourceId
        this.$refs.entityList.setList(this.entityQuery)
        this.$refs.entityList.handleCheck()
      } else {
        this.$message.warning('请先选择表')
      }
    },
    load(tree, treeNode, resolve) {
      resolve(tree.children)
    },
    getListByTreeId(data) {},
    getList() {
      if (!this.listQuery.sourceId) {
        this.$message.error('请选择一个数据表')
        return
      }
      this.listLoading = true
      fetchcolumnList(this.listQuery).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
        this.setSort()
        this.listLoading = false
      })
    },
    handleUpdate(row) {
      this.$refs.form.setList(this.labelList)
      this.$refs.form.handleUpdate(row.id)
    },
    handleUpdate1(row) {
      this.$confirm('确定解除标签绑定吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const data = row
        data.labelId = ''
        updatecolumn(data).then((response) => {
          this.loading = false
          if (response.data.code === 0) {
            this.dialogFormVisible = false
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletecolumn(row.id).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleBathDelete() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定删除所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletecolumn(this.ids).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleImport() {
      this.$refs.import.show()
    },
    handleExport() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.downloadLoading = true
      exportcolumn(this.ids).then((response) => {
        this.downloadLoading = true
        if (response.data.code === 0) {
          import('@/vendor/Export2Excel').then((excel) => {
            excel.export_byte_to_excel(response.data.data.bytes, response.data.data.title)
            this.downloadLoading = false
          })
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    setSort() {
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        setData: function (dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: (evt) => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)
          // TODO：这里完成自己的业务处理
        },
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
  },
}
</script>
<style lang="scss">
#treeBox {
  margin-top: 1px;

  .el-table thead {
    display: none;
  }
}
.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}
.left-tree {
  position: relative;
  // width: 500px;
  // height: 100%; // 如果存在box-sizing，此处设置就会用会影响，可以先去掉看看效果
  background: #fff;
  // box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.050980392156862744);
  border-radius: 4px;
  vertical-align: top;
  display: inline-block;
  box-sizing: border-box;
  -ms-flex-negative: 0;
  flex-shrink: 0;
  padding: 10px 0 0 10px;
  // margin-right: 8px;
}
.resize {
  cursor: col-resize;
  position: absolute;
  top: 45%;
  right: -8px;
  background-color: #d6d6d6;
  border-radius: 5px;
  margin-top: -10px;
  width: 10px;
  height: 50px;
  background-size: cover;
  background-position: 50%;
  font-size: 32px;
  color: #fff;
  display: flex; /* 使用 flex 布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}
.right-content {
  display: inline-block;
  width: calc(100% - 510px);
  height: 100%;
  background: #fff;
  -webkit-box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.050980392156862744);
  box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.050980392156862744);
  border-radius: 4px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 10px;
  vertical-align: top;
  overflow: auto;
}
</style>
